﻿


$(function () {
    _vmBase = new viewModel();

    _vmBase.init();
})

function viewModel() {
    var me = this;
    VueViewModelBase.call(me);
    viewModelExtend.call(me);


    me.tableListUrl = _getTableListUrl;
   
    me.tabObj = $('#tb_features');

    me.uiViewButtonTab;
    

    //重写方法
    me.init = function () {

        //资源类型加载成功后初始化Table
        me.GetResourceTypeSelect(function (result) {
            me.initTableList();
        });

        $('#uiViewButtonsDiv').hide();

        me.bindEventToBtn();
    }

    me.initTableList = function () {

        var options = {
            search: false,
            singleSelect: true,
            columns: [
                {
                    checkbox: true
                },
                {
                    field: 'code',
                    title: '编码',
                    sortable:true,
                    filterControl: "input"
                },
                {
                    field: 'type',
                    title: '类型',
                    filterControl: "select",
                    formatter: function (value, row, index) {
                        if (row.type == _featuresUIViewType) {
                            return "视图";
                        } else if (row.type == _featuresFuncType) {
                            return "功能";
                        }
                    }
                },
                {
                    field: 'resourceTypeId',
                    title: '所属资源',
                    filterControl: "select",
                    filterData: "var:_resourceTypeSelect",
                    formatter: function (value,row,index) {
                        return row.resourceTypeName;
                    }
                },
                {
                    field: 'resourceTypeCode',
                    title: '所属资源编码'
                },
                {
                    field: 'description',
                    title: '描述'
                    
                },
                {
                    field: 'isManage',
                    title: '是否托管',
                    filterControl: "select",
                    filterData:"var:_isManageSelect",
                    formatter: function (value, row, index) {
                        var enabledLabel = '<span class="label label-info" id="' + row.id + '">' + _isMangeStr + '</span>';
                        var disabledLabel = '<span class="label label-warning" id="' + row.id + '">' + _isNotManageStr + '</span>';
                        if (row.isManage) {
                            return enabledLabel;
                        } else {
                            return disabledLabel;
                        }
                    }
                },
                {
                    field: 'status',
                    title: '状态',
                    formatter: function (value, row, index) {
                        var enabledLabel = '<span class="label label-success" id="' + row.id + '">' + _enabledStr + '</span>';
                        var disabledLabel = '<span class="label label-default" id="' + row.id + '">' + _disabledStr + '</span>';
                        if (row.status) {
                            return enabledLabel;
                        } else {
                            return disabledLabel;
                        }
                    }
                }
                
            ],
            filterControl: true,
            //filterTemplate: {}, //修改了bootstrap-table-filter-control.js源码,placeholder默认为undefined,不会渲染input
            queryParams: function (params) {
                var filter = "";
                if (params.filter != undefined && params.filter != null) {
                    filter = params.filter;
                }
                var sortName = params .sort;
                var sortOrder = params .order;
                
                var temp = {
                    rows: params.limit,                         //页面大小
                    page: (params.offset / params.limit) + 1,   //页码
                    queryKey: vueModel.queryKey,
                    treeId: vueModel.treeId,
                    filter: filter,
                    sortName: sortName,
                    sortOrder: sortOrder
                };
                return temp;
            },
            onClickRow: function (row, $element) {
                if (row.type == _featuresUIViewType) {
                    //$dh.msg("视图");
                    //加载视图按钮列表
                    $('#uiViewButtonsDiv').show();
                    me.loadUiViewFuncs(row.resourceTypeId, function (result) {

                        me.loadUiViewButtons(result);

                    });

                } else if (row.type == _featuresFuncType) {
                    //destory  视图按钮列表
                    $('#uiViewButtonsDiv').hide();
                    if (me.uiViewButtonTab != null && me.uiViewButtonTab != undefined) {
                        me.uiViewButtonTab.bootstrapTable('destroy');
                    }
                }
            },
            onCheck: function (row) {
                //if (row.type == _featuresUIViewType) {
                //    //$dh.msg("视图");
                //    //加载视图按钮列表
                //    $('#uiViewButtonsDiv').show();
                //    me.loadUiViewFuncs(row.resourceTypeId, function (result) {

                //        me.loadUiViewButtons(result);

                //    });

                //} else if (row.type == _featuresFuncType) {
                //   //destory  视图按钮列表
                //    $('#uiViewButtonsDiv').hide();
                //    if (me.uiViewButtonTab != null && me.uiViewButtonTab != undefined) {
                //        me.uiViewButtonTab.bootstrapTable('destroy');
                //    }
                //}
            },
            onUncheck: function (row) {
                $('#uiViewButtonsDiv').hide();
                if (me.uiViewButtonTab != null && me.uiViewButtonTab != undefined) {
                    me.uiViewButtonTab.bootstrapTable('destroy');
                }

            }

        }
        me.initList(options);

    }


    

}

function viewModelExtend() {
    var me = this;

   
    //初始化系统功能集
    me.InitFeatures = function () {
        $dh.get(_initResource, null, function (result) {
            if (result.Status == ResultStatus.OK) {
                $dh.msg(result.Msg);
                _vmBase.search();

                //重新获取下来数据
                me.GetResourceTypeSelect(function (result) {

                });
            } else {
                $dh.alert(result.Msg);
            }

        });
    }

    //获取资源类型下来数据源
    me.GetResourceTypeSelect = function (callback) {
        $dh.get(_getResourceTypeUrl, null, function (result) {
            _resourceTypeSelect = result;
            callback(true);
        });
    }

    //加载视图功能
    me.loadUiViewFuncs = function (resourceId, callback) {

        $dh.get(_getFuncsUrl, { resourceId: resourceId }, function (result) {

            //获取功能后，生成下来数据

            var seles = "<select> ";

            seles += '<option value=""></option>';
            for (var i = 0; i < result.length; i++) {
                var op = '<option value ="' + result[i].id + '">' + result[i].description + '</option>';
                seles += op;
            }
            seles += "</select>";

            callback(seles);
        });

    }

    //加载视图按钮
    me.loadUiViewButtons = function (selectElements) {
        if (me.uiViewButtonTab != null && me.uiViewButtonTab != undefined) {
            me.uiViewButtonTab.bootstrapTable('destroy');
        }
        var viewButtonTab = $('#tb_uiViewButtons').bootstrapTable({
            url: _getButtonsUrl,
            method: 'get',                      //请求方式（*）
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded",
            //toolbar: '',                //工具按钮用哪个容器
            striped: true,                      //是否显示行间隔色
            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
            pagination: false,                   //是否显示分页（*）
            clickToSelect: true,                //是否启用点击选中行
            uniqueId: "Id",                     //每一行的唯一标识，一般为主键列
            detailView: false,                    //显示子表
            columns: [{
                checkbox: true

            }, {
                field: 'name',
                title: '按钮名称',

            },
            {
                field: 'icon',
                title: '图标',
                formatter: function (value, row, index) {
                    return '<i class="' + row.icon + '"></i>';
                }
            }, {

                filed: 'funcId',
                title: '功能',

                formatter: function (value, row, index) {
                    //生成下拉框
                    //var funcSels = '<select onchange="_vmBase.btnFunSelectChange(this,' + index+')"> ';
                    //funcSels = funcSels + selectElements;
                    var funcSels = selectElements;
                    return funcSels;
                }
            }, {

                filed: 'sortIndex',
                title: '页面按钮序号',
                formatter: function (value, row, index) {
                    //生成文本框
                    var sortTxt = '<input type="number"  name="SortIndex" /> ';

                    return sortTxt;
                }
            }, {
                field: 'id',
                title: '',
                cellStyle: function (value, row, index) {
                    return {
                        css: { "display": "none" }
                    }
                }

            }

            ],
            onCheck: function (row) {

            },
            onUncheck: function (row) {

            },
            onCheckAll: function (rows) {

            },
            onUncheckAll: function (rows) {


            },
            onLoadSuccess: function (data) {
                //按钮列表加载完毕,加载有权限按钮
                var selectUiViewRows = $('#tb_features').bootstrapTable('getSelections');
                var selectUiViewObj = selectUiViewRows[selectUiViewRows.length - 1];
                if (selectUiViewObj != null && selectUiViewObj != undefined) {
                    me.getUiViewBtnFuncs(selectUiViewObj.id);
                }
                
            }

        });

        me.uiViewButtonTab = viewButtonTab;

        
    }


    me.submitUiViewBtnFuncs = function () {
        var selectUiViewRows = $('#tb_features').bootstrapTable('getSelections');
        var selectUiViewObj = selectUiViewRows[selectUiViewRows.length - 1];


        var isError = false;
        var btnFuncs = [];

        var selTrs = $('#tb_uiViewButtons tr[class="selected"]');
        for (var i = 0; i < selTrs.length; i++) {
            var selTd = $(selTrs[i]).find('td')[3];
            var selFuncValue = $(selTd).find('select').val();

            var selBtnTd = $(selTrs[i]).find('td')[5];
            var selBtnId = $(selBtnTd).html();

            var selBtnSortIndexTd = $(selTrs[i]).find('td')[4];
            var selBtnSortIndex = $(selBtnSortIndexTd).find('input').val();

            var btnFunObj = {};
            btnFunObj.UiViewId = selectUiViewObj.id;
            btnFunObj.ButtonId = selBtnId;
            btnFunObj.FeatureId = selFuncValue;
            btnFunObj.SortIndex = selBtnSortIndex;

            if (selFuncValue == "" || selFuncValue == null || selFuncValue == undefined) {
                isError = true;
                break;
            }

            btnFuncs.push(btnFunObj);
            
        }
        if (isError) {
            $dh.alert("请为选中的按钮选择功能！");
            return;
        }
        
        

        $dh.post(_saveUiViewFeaturesUrl, { viewDtos: btnFuncs}, function (result) {
            if (result.Status == ResultStatus.OK) {

                $dh.msg("存储成功");

            } else {
               
                $dh.msg("存储失败");
            }

        });



    }

    me.getUiViewBtnFuncs = function (uiViewId) {

        $dh.get(_getUiViewFeaturesUrl, { uiViewId: uiViewId}, function (result) {
            //勾选按钮
            var btnIds = [];
            for (var i = 0; i < result.length; i++){
                btnIds.push(result[i].buttonId);
                
            }

            $("#tb_uiViewButtons").bootstrapTable("checkBy", { field: "id", values: btnIds });

            //选中下拉框
            var selTrs = $('#tb_uiViewButtons tr[class="selected"]');
            for (var i = 0; i < selTrs.length; i++) {
                var selTd = $(selTrs[i]).find('td')[3];
                var selFuncObj = $(selTd).find('select');

                var selBtnTd = $(selTrs[i]).find('td')[5];
                var selBtnId = $(selBtnTd).html();

                var selBtnSortTd = $(selTrs[i]).find('td')[4];
                var selBtnSortIndexObj = $(selBtnSortTd).find('input');

                for (var fi = 0; fi < result.length; fi++){
                    var btnId = result[fi].buttonId;
                    if (btnId == selBtnId) {
                        selFuncObj.val(result[fi].featureId);

                        selBtnSortIndexObj.val(result[fi].sortIndex);
                    }

                }

               
            }

        });
    }

    me.bindEventToBtn = function () {
        var btnInitId = "Features_Index_btnInit";
        var $obj = $('#' + btnInitId);
        if ($obj) {
            var innerHtml = $obj.html();
            var sliceIndex = innerHtml.indexOf('</i>');
            if (sliceIndex > 0) {
                innerHtml = innerHtml.substr(0, sliceIndex + 4);
                innerHtml += _initFeatureStr;
                $obj.html(innerHtml);
                $obj.on("click", me.InitFeatures);
            }
        }
    }

}
